import collections
import datetime
import time

from django.db.models import Count
from django.http import JsonResponse
from django.shortcuts import render

from web import models


def dashboard(request,project_id):
    # status_dict = {}
    #
    # Issues_objs = models.Issues.objects.filter(project_id=project_id)
    #
    #
    #
    # context = {
    #     'status_dict':status_dict,
    # }

    # 问题数据处理
    status_dict = collections.OrderedDict()#py3.6 之前的字典是无序的！故使用OrderedDict
    # print('-------1------')
    # print(models.Issues.status_choices)
    for key, text in models.Issues.status_choices:
        # print(key, text)
        status_dict[key] = {'text': text, 'count': 0}

    issues_data = models.Issues.objects.filter(project_id=project_id).values('status').annotate(ct=Count('id'))
    #为每个issue遍历一遍，并按照status进行计数
    for item in issues_data:
        status_dict[item['status']]['count'] = item['ct']

    # 项目成员
    user_list = models.ProjectUser.objects.filter(project_id=project_id).values('user_id', 'user__user_name')

    # 最近的10个问题 更具实际需求显示不同的东西
    top_ten = models.Issues.objects.filter(project_id=project_id, assign__isnull=False).order_by('-id')[0:10]

    context = {
        'status_dict': status_dict,
        'user_list': user_list,
        'top_ten_object': top_ten
    }

    return render(request,'dashboard.html',context=context)


def issues_chart(request,project_id):
    #给dashboard概揽图表 传递数据
    #图表绘制 最近30天内，每天创建的问题数量

    #想数据库查询最近30天内的所有数据 & 并根据每一天分组


    today = datetime.datetime.now().date()

    result = models.Issues.objects.filter(project_id=project_id,create_datetime__gte=today - datetime.timedelta(days=30)).extra(
        select={"ctime":"strftime('%%Y-%%m-%%d',web_issues.create_datetime)"}
        ##.extra() 用于额外的高级SQL语句  其中strftime 为sqlite的高级语法函数  如果是mysql则是另外的
        #select={"ctime":"strftime('%%Y-%%m-%%d',web_issues.create_datetime)"}
        ## 相当于  select strftime('%Y-%m-%d',web_issues.create_datetime) as ctime from ...
    ).values('ctime').annotate(ct=Count('id'))

    # result = models.Issues.objects.filter(project_id=project_id,
    #                                       create_datetime__gte=today - datetime.timedelta(days=30)).extra(
    #     select={'ctime': "strftime('%%Y-%%m-%%d',web_issues.create_datetime)"}).values('ctime').annotate(ct=Count('id'))


    date_dict = collections.OrderedDict()
    for i in range(0, 30):
        date = today - datetime.timedelta(days=i)
        date_dict[date.strftime("%Y-%m-%d")] = [time.mktime(date.timetuple()) * 1000, 0]
        #将30天的日期转换为时间戳格式供前端使用

    # print(result)

    for item in result:
        date_dict[item['ctime']][1] = item['ct']

    # return JsonResponse({'data':date_dict})#......你在干什么？？
    # print(date_dict)
    # print(date_dict.values())
    # print(list(date_dict.values()))
    return JsonResponse({'status': True, 'data': list(date_dict.values())})